package com.jjrwa.action;

import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

public class AddNoArgsConstructorQuickFix implements LocalQuickFix {

    @Override
    public @Nls @NotNull String getName() {
        return "Add @NoArgsConstructor";
    }

    @Override
    public @Nls @NotNull String getFamilyName() {
        return "Add @NoArgsConstructor";
    }

    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
        // 获取当前类元素
        PsiElement element = descriptor.getPsiElement();
        if (element == null || !(element.getParent() instanceof PsiClass)) {
            return;
        }
        PsiClass psiClass = (PsiClass) element.getParent();

        // 创建 @NoArgsConstructor 注解字符串
        String annotationText = "NoArgsConstructor";

        // 将注解添加到类上
        PsiModifierList modifierList = psiClass.getModifierList();
        if (modifierList != null) {
            modifierList.addAnnotation(annotationText);
        }

        // 自动导入 Lombok @NoArgsConstructor 注解
        PsiImportList importList = ((PsiJavaFile) psiClass.getContainingFile()).getImportList();
        if (importList != null) {
            addImportIfNeeded(importList, "lombok");
        }
    }

    /**
     * 自动添加导入语句（如果没有的话）
     */
    private void addImportIfNeeded(PsiImportList importList, String className) {
        PsiImportStatementBase importStatement = importList.findSingleImportStatement(className);
        if (importStatement == null) {
            PsiElementFactory factory = JavaPsiFacade.getElementFactory(importList.getProject());
            PsiImportStatementBase newImport = factory.createImportStatementOnDemand(className);
            importList.add(newImport);
        }
    }
}
